const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      bodyparser = require('koa-bodyparser'),
      hq = require('./login.js')
const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}

app.use(bodyparser());

app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/login'||ctx.url ==='/login/get' || ctx.url === '/logininsert' || ctx.url === '/loginupdate'||ctx.url === '/logindel' ) {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
//给权限
router.post('/login',async (ctx)=>{
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;
  //log(ctx.request.body);
  let arr = await hq.getlogin(username,password);
  if(arr.length==0) ctx.body = JSON.stringify('失败');
  else if(arr.length==1) ctx.body = JSON.stringify('成功');
})
//返回
router.post('/login/get',async (ctx)=>{
  let arr = await hq.getlogin1();
  ctx.body = JSON.stringify(arr);
})
//添加
router.post('/logininsert',async (ctx)=>{
  //let {username,password} =ctx.request.query;
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;
  await hq.insertl(username,password);
  let arr = await hq.getlogin1();
  ctx.body = JSON.stringify(arr);
})
//修改
router.post('/loginupdate',async (ctx)=>{
  //let {id,username,password} =ctx.request.query;
  let id = ctx.request.body.id;
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;
  await hq.upl(id,username,password);
  let arr = await hq.getlogin1();
  ctx.body = JSON.stringify(arr);
})
//删除接口
router.post('/logindel',async (ctx)=>{
  //let {id} =ctx.request.query;
  let id = ctx.request.body.id;
  await hq.dell(id);
  let arr = await hq.getlogin1();
  ctx.body = JSON.stringify(arr);
})
process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

app.use(router.routes())
   .use(router.allowedMethods());

https.createServer(options,app.callback()).listen(2001);
//app.listen(2001);

